<?php

namespace App\Admin\SDK\IBay;

// ibay SDK by Martin
class Core{

    const BASE_URL = '/index.php/api';

    protected $url;

    protected $success;

    protected $debug;

    protected $http;


    public function __construct()
    {
        $this->http = new \GuzzleHttp\Client();
        $this->url = 'http://'.config('ibay.api')['host'].self::BASE_URL;
    }


    // 设置或返回debug
    public function debug($data='')
    {
        if ($data) {
            $this->debug = $data;
            return false;
        } else {
            return $this->debug;
        }

    }




    /**
     * curl 请求
     * @param $url
     */
    protected function request($url, $method='GET'): bool
    {
//        \Log::info($url);

        try{
            $response = $this->http->request($method, $url);

//            \Log::info($response->getStatusCode());
//            \Log::info($response->getBody());

            if ($response->getStatusCode() == 200) {
                $obj= $response->getBody();
                $obj = json_decode($obj);

                if ($obj->ack == 'success') {
//                    $this->success =  $obj->getskusResponse->list;
                    $this->success =  $obj;

                    return true;
                } else {
                    return $this->debug($obj->message);
                }

            } else {
                return $this->debug($response->getStatusCode());
            }

        }catch (\Exception $e) {
            return $this->debug($e->getMessage());
        }


        # old code
        /*try{

            $obj = curlGet($url);

            $obj = json_decode($obj);

            if ($obj->ack == 'success') {
                $this->success =  $obj->getskusResponse->list;

                \Log::info(json_encode($obj->getskusResponse->pagination));
                return true;
            } else {
                //{"ack":"failure","message":"Operation auth not existed."}
                return $this->debug($obj->message);
            }

        }catch (\Exception $e) {
            return $this->debug($e->getMessage());
        }*/
    }


    /**
     * 获取返回数据
     * @return mixed
     */
    public function response(): object
    {
        return $this->success;
    }


}